package org.bikelab.se3.rdf.reader;

import java.io.InputStream;
import java.util.Iterator;

import org.semanticweb.yars.nx.Literal;
import org.semanticweb.yars.nx.Node;
import org.semanticweb.yars.nx.Resource;

import com.hp.hpl.jena.graph.Triple;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.Statement;

public class N3Parser implements Iterator<Node[]> {
	Model model;
	Iterator<Statement> triples;
	
	public N3Parser(InputStream in) {
		model = ModelFactory.createDefaultModel();
		model.read(in, null, "N3");
		triples = model.listStatements();
	}
	
	@Override
	public boolean hasNext() {
		boolean has = triples.hasNext();
		if(!has) {
			model.close();
		}
		return has;
	}

	@Override
	public Node[] next() {
		// TODO Auto-generated method stub
		return toNodes(triples.next());
	}

	@Override
	public void remove() {
		// TODO Auto-generated method stub

	}
	
	public Node[] toNodes(Statement t) {
		Node[] nodes = new Node[3];
		nodes[0] = new Resource(t.getSubject().getURI());
		nodes[1] = new Resource(t.getPredicate().getURI());
		if(t.getObject().isURIResource()) {
			nodes[2] = new Resource(t.getObject().asNode().getURI());
		} else {
			nodes[2] = new Literal(t.getObject().toString());
		}
		return nodes;
	}
}
